<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title>网上购票</title>
<link rel="stylesheet" href="resources/css/frozen.css">
<link rel="stylesheet" href="resources/css/main.css">
<style>
.quntity {
    color: red;
	font-weight: bold;
}
.friend-name-row {
	padding-bottom: 5px;
}
.take-children-label {
	margin-left: 20px;
}
</style>
<script src="resources/lib/zepto.min.js"></script>
<script src="resources/js/frozen.js"></script>
<script src="resources/js/config.js"></script>
<script src="resources/js/main.js"></script>

</head>
<body ontouchstart="">
	<header class="ui-header ui-header-positive ui-border-b">
		<i class="ui-icon-return" onclick="history.back()"></i>
		<h1>提交订单</h1>
	</header>
	<footer class="ui-footer ui-footer-btn">
		<ul id="footer" class="ui-tiled ui-border-t">
			<li data-href="index.html" class="ui-border-r">
				<div>查询购票</div>
			</li>
			<li data-href="order.html" class="ui-border-r">
				<div>订单查询</div>
			</li>
			<li data-href="member.html">
				<div>会员中心</div>
			</li>
		</ul>
	</footer>
	<section class="ui-container">
		<section class="ui-selector">
			<section id="friend-container" style="display: none;">
				<header>
					<ul class="ui-row-flex">
						<li class="ui-col ui-flex ui-col ui-flex-pack-start">选择乘车人</li>
					</ul>
				</header>
				<div id="friend-list" class="ui-list ui-list-pure ui-border-t">
				</div>
			</section>
			<div class="ui-btn-wrap">
				<button id="btn-add-friend" class="ui-btn-lg ui-btn-primary" style="display: none;">
					添加新联系人
				</button>
			</div>
			<header>
				<h3>订单信息</h3>
			</header>
			<div class="ui-form ui-border-t">
				<form action="#">
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="member-name">订票人</label>
						<input id="member-name" type="text" value="" readonly>
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="route-name">线路</label>
						<input id="route-name" type="text" value="" readonly>
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="bus-id">车次</label>
						<input id="bus-type" type="hidden" value="">
						<input id="bus-id" type="text" value="" readonly>
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="bus-date">乘车日期</label>
						<input id="bus-date" type="text" value="" readonly>
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="bus-start-time">发车时间</label>
						<input id="bus-start-time" type="text" value="" readonly>
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="full-price">全票价</label>
						<input id="full-price" type="text" value="" readonly>
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="full-quantity">全票人数</label>
						<input id="full-quantity" type="tel" class="quntity" value="0">
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="half-price">半票价</label>
						<input id="half-price" type="text" value="" readonly>
					</div>
					<div class="ui-form-item ui-form-item-show ui-border-b">
						<label for="half-quantity">半票人数</label>
						<input id="half-quantity" type="tel" class="quntity" value="0">
					</div>
					<div id="children-quantity-container" class="ui-form-item ui-form-item-show ui-border-b" style="display: none;">
						<label for="children-quantity">携童票数</label>
						<input id="children-quantity" type="text" class="quntity" value="0">
					</div>
				</form>
			</div>
			<div class="ui-btn-wrap">
				<button id="btn-submit" class="btn-group ui-btn-lg ui-btn-primary">
					提交订单
				</button>
			</div>
			<div class="ui-whitespace">
				<h1 class="ui-txt-warning">温馨提示：</h1>
				<p class="ui-txt-justify">1. 成人及身高超过1.5米的儿童乘车，请购买全票。</p>
				<p class="ui-txt-justify">2. 身高1.2米～1.5米的儿童乘车，请购买半票。</p>
				<p class="ui-txt-justify">3. 身高1.2米以下、不单独占用座位的儿童乘车免票。携带免票儿童的乘客须购买全票，并勾选“携童”选择框。若携带免票儿童超过一人，或要求提供座位时，须另外购买半票。</p>
				<p id="real-name-sell-note" class="ui-txt-justify">4. 互联网售票实行实名制，请准确选择乘车人。</p>
			</div>
		</section>
	</section>

	<div id="loading" class="ui-loading-block hide">
		<div class="ui-loading-cnt">
			<i class="ui-loading-bright"></i>
			<p>努力加载中...</p>
		</div>
	</div>
<script>
// 检查登录状态
//checkLogin();

var friendIdSet = new Set();
var seatList = [];

(function (){
	/* -------------------- 根据sessionStorage中的值，初始化界面 -------------------- */

	if(!!sessionStorage.message) {
		showInfoTip(sessionStorage.message);
		sessionStorage.message = "";
	}

	/* -------------------- 根据localStorage中的值，初始化界面 -------------------- */

	// 加载用户名
	$("#member-name").val(sessionStorage.memberName);

	// 加载身份证号
	$("#id-card").val(sessionStorage.idCard);

	// 加载线路
	$("#route-name").val(sessionStorage.orderRouteName);

	// 加载车次
	$("#bus-id").val(sessionStorage.orderBusId);

	// 加载车次类型
	$("#bus-type").val(sessionStorage.orderBusType);

	// 加载乘车日期
	$("#bus-date").val(sessionStorage.orderBusDate);

	// 加载发车时间
	$("#bus-start-time").val(sessionStorage.orderBusStartTime);

	// 加载全票价
	$("#full-price").val(sessionStorage.orderFullPrice);

	// 加载半票价
	$("#half-price").val(sessionStorage.orderHalfPrice);

	// 是否显示携童
	if(appConfig.takeChildren) {
		$("#children-quantity-container").show();
	}

	// 根据系统参数，判断是否实名售票
	if(!!appConfig.realNameSell) {
		// 实名售票
		$("#friend-container").show(); // 显示联系人列表
		$("#full-quantity").attr("readonly", "readonly"); // 全票数不可编辑
		$("#half-quantity").attr("readonly", "readonly"); // 半票数不可编辑
		$("#children-quantity").attr("readonly", "readonly"); // 携童票数不可编辑
		$("#btn-add-friend").show(); // 显示添加新联系人按钮
		$("#real-name-sell-note").show(); // 显示实名售票说明

		// 加载联系人
		loadFriends();
	} else {
		// 非实名售票
	}

	// 联系人姓名点击事件
	$(document).on("tap", "#friend-list .friend-name", function(){
		var row = $(this).parents(".row");
		var selectFriend = row.find(".select-friend");
		if(selectFriend.prop("checked")) {
			selectFriend.prop("checked", false);
		} else {
			selectFriend.prop("checked", true);
		}
		selectFriend.trigger("change");
	});

	// 联系人选择改变事件
	$(document).on("change", ".select-friend", function(){
		var row = $(this).parents(".row");
		var actionRow = row.find(".action-row");
		if($(this).attr("checked")) {
			actionRow.show();
		} else {
			actionRow.hide();
		}

		refreshFriendName(row);
	});

	// 票种开关点击事件
	$(document).on("change", "#friend-list .ticket-type", function(){
		var row = $(this).parents(".row");

		var ticketType = row.find(".ticket-type:checked").val();
		var takeChrildrenLabel = row.find(".take-children-label");
		var takeChrildren = row.find(".take-children");

		// 半票不允许附加携童票
		if(ticketType==1 && appConfig.takeChildren) {
			takeChrildrenLabel.show();
			takeChrildren.show();
		} else if(ticketType==2) {
			takeChrildrenLabel.hide();
			takeChrildren.hide();
			takeChrildren.prop("checked", false);
		}

		refreshFriendName(row);
	});

	// 携童选择事件
	$(document).on("change", "#friend-list .take-children", function(){
		var row = $(this).parents(".row");
		refreshFriendName(row);
	});

	// 添加新联系人按钮点击事件
	$("#btn-add-friend").tap(function(){
		location.href = "addFriend.html";
	});

	// 提交按钮点击事件
	$("#btn-submit").tap(function(){
		submitOrder();
	});

	// 底部主菜单初始化
	initFooter("#footer");
})();

// 查询联系人
function loadFriends() {
	// 查询并加载联系人
	showLoading("#loading");
	ajax({
		url: appConfig.baseUrl + "/BusTicketOrder.go",
		data: {
			method: "getMemberFriendsByMember",
			memberId: sessionStorage.memberId
		},
		success: function(data) {
			hideLoading("#loading");

			if(!!data.rows) {
				if(data.rows.length>0) {
					// 显示联系人
					for(var i=0; i<data.rows.length; i++) {
						var record = data.rows[i];
						$("#friend-list").append(
							"<li class='row ui-border-b' friend-id='" + record.Id +
							"' friend-name='" + record.LinkmanName +
							"' id-card='" + record.LinkmanCredit +
							"' mobile='" + record.LinkmanPhone + "'>" +
								"<div class='friend-name-row'>" +
									"<label class='select-friend-checkbox ui-checkbox'>" +
										"<input class='select-friend' type='checkbox'>" +
									"</label>" +
									"<span class='friend-name'>" +
										record.LinkmanName +
									"</span>" +
								"</div>" +
								"<div class='action-row' style='display:none;'>" +
									"<label>票种：</label>" +
									"<label class='ui-radio ticket-type-radio'>" +
										"全票 <input class='ticket-type' type='radio' name='ticktype" + (i + 1) + "' value='1' checked>" +
										"&nbsp;&nbsp;半票 <input class='ticket-type' type='radio' name='ticktype" + (i + 1) + "' value='2'>" +
									"</label>" +
									"<label class='take-children-label' " + (appConfig.takeChildren ? "" : "style='display: none;'") + ">携童：</label>" +
									"<label class='ui-checkbox take-children-checkbox' " + (appConfig.takeChildren ? "" : "style='display: none;'") + ">" +
										"<input class='take-children' type='checkbox'>" +
									"</label>" +
								"</div>" +
							"</li>"
						);
					}
				}
			} else {
				$("#empty-text").html("联系人加载失败，请重试");
				$("#empty-text").show();
			}
		}
	});
}

// 刷新联系人，显示票种，是否携童，提高用户体验
function refreshFriendName(row) {
	var friendNameContainer = row.find(".friend-name");
	var friendName = row.attr("friend-name");
	var selectFriendChecked = row.find(".select-friend").attr("checked");
	var ticketType = row.find(".ticket-type:checked").val();
	var takeChildrenChecked = row.find(".take-children").attr("checked");

	// 联系人是否选中，选中的联系人，显示票种、是否携童；未选中的只显示姓名
	if(!!selectFriendChecked) {

		if(ticketType==1) {
			friendName += "（全票";
		} else if(ticketType==2) {
			friendName += "（半票";
		}

		if(!!takeChildrenChecked) {
			friendName = friendName + "+携童";
		} else {
			friendName = friendName + "";
		}

		friendName += "）";
	}

	friendNameContainer.html(friendName);

	sumQuantity();
}

// 计算座位、票数、票价
function sumQuantity() {
	// 清空座位列表
	seatList = [];
	fullQuantity = 0;
	halfQuantity = 0;
	childrenQuantity = 0;

	// 遍历联系人列表
	$(".row").each(function(index){
		var row = $(this);

		var selectFriendChecked = row.find(".select-friend").attr("checked");
		var ticketType = row.find(".ticket-type:checked").val();
		var takeChildrenChecked = row.find(".take-children").attr("checked");

		// 只统计已选中的联系人
		if(!!selectFriendChecked) {
			var seat = {
				IsChildren: 0,
				PassengerName: row.attr("friend-name"),
				PassengerIDCard: row.attr("id-card"),
				PassengerPhone: row.attr("mobile"),
				TicketType: 1
			};

			// 票种
			if(ticketType==1) {
				seat.TicketType = 1;
				fullQuantity++;
			} else if (ticketType==2) {
				seat.TicketType = 2;
				halfQuantity++;
			}

			// 携童
			if(!!takeChildrenChecked) {
				seat.IsChildren = 1;
				childrenQuantity++;
				fullQuantity--;
			} else {
				seat.IsChildren = 0;
			}

			seatList.push(seat);
		}

		$("#full-quantity").val(fullQuantity);
		$("#half-quantity").val(halfQuantity);
		$("#children-quantity").val(childrenQuantity);
	});
}

// 提交订单
function submitOrder() {
	var fullQuantity = parseInt($.trim($("#full-quantity").val()));
	var halfQuantity = parseInt($.trim($("#half-quantity").val()));
	var childrenQuantity = parseInt($.trim($("#children-quantity").val()));

	// 根据系统参数，判断是否实名售票
	if(!!appConfig.realNameSell) {
		// 实名售票
		sumQuantity();

		if(fullQuantity+halfQuantity+childrenQuantity==0) {
			showInfoTip("请选择乘车人");
			return;
		}
	} else {
		// 非实名售票
		if(isNaN(fullQuantity)) {
			showInfoTip("请填写正确的全票人数");
			return;
		} else {
			$("#full-quantity").val(fullQuantity);
		}

		if(isNaN(halfQuantity)) {
			showInfoTip("请填写正确的半票人数");
			return;
		} else {
			$("#half-quantity").val(halfQuantity);
		}

		if(isNaN(childrenQuantity)) {
			showInfoTip("请填写正确的携童票数");
			return;
		} else {
			$("#children-quantity").val(childrenQuantity);
		}

		if(childrenQuantity>fullQuantity) {
			showInfoTip("携童票数不可大于全票数");
			return;
		}

		seatList = [];
		for(var i=1; i<=fullQuantity; i++) {
			var seat = {
				IsChildren: 0,
				PassengerName: sessionStorage.memberName,
				PassengerIDCard: sessionStorage.idCard,
				PassengerPhone: sessionStorage.mobile,
				TicketType: 1
			};

			// 若携童票数为n张，则前n张全票携童
			if(childrenQuantity>=i) {
				seat.IsChildren = 1;
			}
			seatList.push(seat);
		}

		for(var i=1; i<=halfQuantity; i++) {
			var seat = {
				IsChildren: 0,
				PassengerName: sessionStorage.memberName,
				PassengerIDCard: sessionStorage.idCard,
				PassengerPhone: sessionStorage.mobile,
				TicketType: 2
			};

			seatList.push(seat);
		}

		if(fullQuantity+halfQuantity==0) {
			showInfoTip("请填写人数");
			return;
		}
	}

	var postData = {
		SellStationID: sessionStorage.orderStartStationId,
		EndStationID: sessionStorage.orderEndStationId,
		stationName: sessionStorage.orderEndStationName,
		BusID: sessionStorage.orderBusId,
		BusTime: sessionStorage.orderBusDate,
		busStartTime: sessionStorage.orderBusStartTime + ':00',
		Full: fullQuantity,
		FullPrice: sessionStorage.orderFullPrice,
		Half: halfQuantity,
		HalfPrice: sessionStorage.orderHalfPrice,
		Children: childrenQuantity,
		getManName: sessionStorage.memberName,
		getManMobile: sessionStorage.mobile,
		proxyId: appConfig.proxyId,
		Seats: seatList,
		CheckGateName: sessionStorage.checkGateName
	};

	showLoading("#loading");
	console.info(JSON.stringify(postData));

	ajax({
		url: appConfig.baseUrl + "/BusTicketOrder.go",
		data: {
			method: "saveOrder",
			record: JSON.stringify(postData)
		},
		failMessage: "提交失败，请重试",
		success: function(data) {
			hideLoading("#loading");

			if(!!data.success) {
				if(!data.id) {
					sessionStorage.payOrderId = data.OrderID;
					location.href = "payOrder.html";
				}
			} else {
				showInfoTip("提交失败");
			}
		}
	});
}
</script>
</body>
</html>